package es.uma.scgt.controlador;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


import es.uma.scgt.modelo.Test;
import es.uma.scgt.servicio.TestService;

@Controller
public class TestController {
	@Autowired
	private TestService studentService;
	
	@RequestMapping("/index")
	public String setupForm(Map<String, Object> map){
		Test student = new Test();
		map.put("student", student);
		map.put("studentList", studentService.getAllStudent());
		return "testStudent";
	}
	@RequestMapping(value="/student.do", method=RequestMethod.POST)
	public String doActions(@ModelAttribute Test student, BindingResult result, @RequestParam String action, Map<String, Object> map){
		Test studentResult = new Test();
		
		if("add".equalsIgnoreCase(action)){
			studentService.add(student);
			studentResult = student;
		}else if("edit".equalsIgnoreCase(action)){
			studentService.edit(student);
			studentResult = student;
		}else if("delete".equalsIgnoreCase(action)){
			studentService.delete(student.getStudentId());
			studentResult = new Test();
		}else if("search".equalsIgnoreCase(action)){
			Test searchedStudent = studentService.getStudent(student.getStudentId());
			studentResult = searchedStudent!=null ? searchedStudent : new Test();
		}
		
		map.put("student", studentResult);
		map.put("studentList", studentService.getAllStudent());
		return "testStudent";
	}
}
